package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @Author mr.lin
 * @Date 2025/1/27 10:27
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    /**
     * 分页查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pageList(WmNewsPageReqDto dto) {
        //1.对page和size进行非空判断
        dto.checkParam();

        //2.获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.判断当前自媒体是否有文章
        Integer count = lambdaQuery().eq(WmNews::getUserId, user.getId())
                .count();
        if (count == null || count == 0) {
            return ResponseResult.errorResult(400, "对不起,您没有文章!");
        }
        //2.构建分页查询条件
        LambdaQueryWrapper<WmNews> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.like(dto.getKeyword() != null && dto.getKeyword() != "", WmNews::getTitle, dto.getKeyword())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //3.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        page = page(page, lambdaQuery);
        //4.构建返回结果
        ResponseResult result = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;


    }


    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;


    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 文章提交审核 或 保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.数据转换(特别是图片)
        WmNews news = new WmNews();
        BeanUtils.copyProperties(dto, news);
        news.setCreatedTime(new Date());
        news.setUserId(WmThreadLocalUtil.getUser().getId()); //用户id
        news.setSubmitedTime(new Date());

        //单独对图片操作
        List<String> imageList = null;  //定义一个内容图片的集合
        List<String> images = dto.getImages();
        if (CollectionUtils.isEmpty(images)) {
            //集合没有,代表自动的 判断内容中图片个数 1<= <3 取出第一个作为封面, 3个以上 取前3个做封面图片 多图封面, 否则无图
            //此时图片在内容中,将内容转为一个list集合
            imageList = getContentImagesList(news);
            //获取到所有的内容图片集合后
            if (imageList.size() == 0) {
                //代表没有图 不用设置 就是null
                news.setType(WemediaConstants.WM_NEWS_NONE_IMAGE); // 图文类型 0 无图
            }
            if (imageList.size() >= 3) {
                //代表多图
                news.setType(WemediaConstants.WM_NEWS_MANY_IMAGE); // 图文类型 3 多图
                String imagesStr = StringUtils.join(imageList, ",");
                news.setImages(imagesStr); //将图片地址以逗号分割 设置到实体类中
            } else {
                //单图,只要第一个
                news.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);// 图文类型 1 单图
                news.setImages(imageList.get(0));
            }
        } else {
            //集合有,代表选择图片
            //将集合中的图片以逗号分割转为String类型
            String imagesStr = StringUtils.join(images, ",");
            news.setImages(imagesStr); //将图片地址以逗号分割 设置到实体类中
        }


        //2.判断是否存在id 存在是修改操作 不存在是新增操作
        insertOrUpdate(news);
        //3.判断是否是草稿 是草稿就不用往下走了 不是草稿要操作中间表
        if (news.getStatus() == 0) {
            return ResponseResult.okResult(null);
        }
        //4.把所有涉及到的图片都存入到中间表中 注意区分图片引用关系
        saveNewsMaterials(images, news);

        //5.调用自动审核业务
        wmNewsAutoScanService.autoScanWmNews(news.getId());
        return ResponseResult.okResult(200, "操作成功");
    }


    /**
     * 获取内容中图片集合
     *
     * @param news
     * @return
     */
    private static List<String> getContentImagesList(WmNews news) {
        List<String> imageList;
        List<Map> list = JSON.parseArray(news.getContent(), Map.class);
        imageList = new ArrayList<>(); //存放内容中图片的集合
        for (Map map : list) {
            String type = (String) map.get("type");
            if ("image".equals(type)) {
                String img = (String) map.get("value");
                imageList.add(img);
            }
        }
        return imageList;
    }

    /**
     * 新增或修改操作
     *
     * @param news
     */
    private void insertOrUpdate(WmNews news) {
        if (news.getId() != null) {
            //修改操作 删除中间表数据
            wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
            updateById(news);
        } else {
            //新增操作
            save(news);
        }
    }

    @Autowired
    private WmMaterialService wmMaterialService;

    /**
     * 批量保存中间表数据
     *
     * @param images
     * @param news
     * @param
     */
    private void saveNewsMaterials(List<String> images, WmNews news) {
        List<WmNewsMaterial> wmNewsMaterials = new ArrayList<>();
        //文章内容以外的图片
        if (images != null && images.size() > 0) {
            for (String image : images) {
                WmNewsMaterial newsMaterial = new WmNewsMaterial();
                newsMaterial.setNewsId(news.getId()); //文章id
                newsMaterial.setType(1); //主图引用
                newsMaterial.setOrd(0); //顺序
                //根据image地址去查询素材表
                WmMaterial one = wmMaterialService.getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, image));
                if (one != null) {
                    newsMaterial.setMaterialId(one.getId());
                }
                wmNewsMaterials.add(newsMaterial);
            }
        }
        //避免 内容图片和封面图片都有的情况,也要把内容图片存入到中间表
        List<String> imageList = getContentImagesList(news);
        //文章内容中的图片
        if (imageList != null && imageList.size() > 0) {
            for (String image : imageList) {
                WmNewsMaterial newsMaterial = new WmNewsMaterial();
                newsMaterial.setNewsId(news.getId()); //文章id
                newsMaterial.setType(0); //内容引用
                newsMaterial.setOrd(0); //顺序
                //根据image地址去查询素材表
                WmMaterial one = wmMaterialService.getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, image));
                if (one != null) {
                    newsMaterial.setMaterialId(one.getId());
                }
                wmNewsMaterials.add(newsMaterial);
            }

        }
        //批量保存中间表数据
        wmNewsMaterialService.saveBatch(wmNewsMaterials);
    }

    /**
     * 文章查询详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        return ResponseResult.okResult(getById(id));
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNew(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(400, "删除的文章不存在");
        }
        //2.判断文章状态  已发布且已上架 不能删
        if (wmNews.getStatus() == 9 && wmNews.getEnable() == 1) {
            return ResponseResult.errorResult(400, "已发布且已上架的文章不能删除");
        }
        //3.删除文章,并且删除中间表
        removeById(id); // 删除文章
        wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id)); // 删除中间表
        return ResponseResult.okResult(200, "删除成功");
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewDto dto) {
        //1.先查询出文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //2.判断文章是否已经发布
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章未发布,不能上下架");
        }
        //3.修改文章状态
        lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable())
                .update();
        return ResponseResult.okResult(200, "修改成功");
    }


}
